#!/use/bin/python
# coding=utf-8
# 早间开机 数据分析-夜间音量-推送成功率
import datetime
import pymysql

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# 记录 数据分析-夜间音量-推送成功率 analysis_yjyl_complete_rate
def insertYjylCompleteRate(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_yjyl_complete_rate 表是否已经存在当天 数据
        selectCountSql = """
                    select count(1) num from analysis_yjyl_complete_rate t where 1=1 and t.ref_date =  '%s'
                """ % date
        cur.execute(selectCountSql)
        result = cur.fetchone()
        countNum = result[0]
        # 获取当日可以执行夜间音量的设备量
        selectNightNumSql = """
                    select count(DISTINCT(t.active_id)) from log_yjyl_auto_change_result t where 1=1 and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d') = '%s'
                """ % date;
        cur.execute(selectNightNumSql)
        resultNightNum = cur.fetchone()
        # 获取当日夜间音量推送次数
        selectNumSql = """
                    select count(DISTINCT(t.active_id)) from log_yjyl_yl t where 1=1 and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d') = '%s' and t.result = 1
                """ % date;
        cur.execute(selectNumSql)
        resultNum = cur.fetchone()
        #计算 当天用户当前音量比经验值小的次数
        selectMinNumSql = """
                    select count(DISTINCT(t.active_id)) from log_yjyl_auto_change_result t where t.result = 0 and t.reason = 'min' and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d') = '%s'
                """ % date;
        cur.execute(selectMinNumSql)
        resultMinNum = cur.fetchone()
        # 计算 当天成功降低音量的次数
        selectSuccessNumSql = """
                            select count(DISTINCT(t.active_id)) from log_yjyl_auto_change_result t where t.result = 1 and DATE_FORMAT(t.create_time, '%%Y-%%m-%%d') = '%s'
                        """ % date;
        cur.execute(selectSuccessNumSql)
        resultSuccessNum = cur.fetchone()
        # 计算夜间音量成功率
        successRate = 0
        newPushNum = resultNum[0]
        nightNum = resultNightNum[0]
        minNum = resultMinNum[0]
        successNum = resultSuccessNum[0]
        if newPushNum!=0:
            if successNum > newPushNum:
                successRate = 100
            else:
                successRate = round(successNum/newPushNum,4)*100

        if countNum == 0:
            logDetail ="%s日新增-夜间音量可以执行夜间音量的设备量为%s,推送次数为%s,用户比当前音量经验值少的数量为%s,成功降低音量的次数为%s,成功率为%s" % (date,nightNum,newPushNum,minNum,successNum,successRate)
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = """insert into analysis_yjyl_complete_rate(night_num,auto_num,min_num,success_num,success_rate,ref_date) 
                value(%s,%s,%s,%s,%s,'%s')""" % (nightNum,newPushNum,minNum,successNum,successRate,date)
            cur.execute(insertSql)
        else:
            logDetail ="%s日更新-夜间音量可以执行夜间音量的设备量为%s,推送次数为%s,用户比当前音量经验值少的数量为%s,成功降低音量的次数为%s,成功率为%s" % (date,nightNum,newPushNum,minNum,successNum,successRate)
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = """
                update analysis_yjyl_complete_rate set night_num = %s , auto_num = %s ,min_num = %s,success_num = %s ,success_rate = %s ,update_time = now()  where
                    ref_date = '%s' 
            """ % (nightNum,newPushNum,minNum,successNum,successRate,date);
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-夜间音量-推送成功率 analysis_yjyl_complete_rate - 月度
def insertYjylCompleteRateMonth(toMonthDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_yjyl_complete_rate 表是否已经存在当月 数据
        selectCountSql = """
                    select count(1) num from analysis_yjyl_complete_rate t where 1=1 and t.ref_date =  '%s'
                """ % toMonthDay
        cur.execute(selectCountSql)
        result = cur.fetchone()
        countNum = result[0]
        # 获取当日可以执行夜间音量的设备量
        selectNightNumSql = """
                    select sum(night_num) from analysis_yjyl_complete_rate t where 1=1 and SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s'
                """ % (toMonthDay,toMonthDay);
        cur.execute(selectNightNumSql)
        resultNightNum = cur.fetchone()
        # 获取当月夜间夜间音量 执行次数
        selectNumSql = """
                    select sum(auto_num) from analysis_yjyl_complete_rate t where 1=1 and SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s'
                """ % (toMonthDay,toMonthDay);
        cur.execute(selectNumSql)
        resultNum = cur.fetchone()
        #计算 当月用户当前音量比经验值小的次数
        selectMinNumSql = """
                    select sum(min_num) from analysis_yjyl_complete_rate t where 1=1 and SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s'
                """ % (toMonthDay,toMonthDay);
        cur.execute(selectMinNumSql)
        resultMinNum = cur.fetchone()
        # 计算 成功降低音量的次数
        selectSuccessNumSql = """
                    select sum(success_num) from analysis_yjyl_complete_rate t where 1=1 and SUBSTR( t.ref_date, 1,7) = '%s' and t.ref_date != '%s'
                """ % (toMonthDay,toMonthDay);
        cur.execute(selectSuccessNumSql)
        resultSuccessNum = cur.fetchone()
        # 计算夜间音量成功率
        successRate = 0
        newPushNum = resultNum[0]
        nightNum = resultNightNum[0]
        minNum = resultMinNum[0]
        successNum = resultSuccessNum[0]
        if newPushNum != 0:
            if successNum > newPushNum:
                successRate = 100
            else:
                successRate = round(successNum / newPushNum, 4) * 100

        if countNum == 0:
            logDetail = "%s月新增-夜间音量可以执行夜间音量的设备量为%s,推送次数为%s,用户比当前音量经验值少的数量为%s,成功降低音量的次数为%s,成功率为%s" % (
            toMonthDay, nightNum, newPushNum, minNum, successNum, successRate)
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = """insert into analysis_yjyl_complete_rate(night_num,auto_num,min_num,success_num,success_rate,ref_date) 
                value(%s,%s,%s,%s,%s,'%s')""" % (nightNum, newPushNum, minNum, successNum, successRate, toMonthDay)
            cur.execute(insertSql)
        else:
            logDetail = "%s月更新-夜间音量可以执行夜间音量的设备量为%s,推送次数为%s,用户比当前音量经验值少的数量为%s,成功降低音量的次数为%s,成功率为%s" % (
            toMonthDay, nightNum, newPushNum, minNum, successNum, successRate)
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = """
                update analysis_yjyl_complete_rate set night_num = %s , auto_num = %s ,min_num = %s,success_num = %s ,success_rate = %s ,update_time = now()  where
                    ref_date = '%s' 
            """ % (nightNum, newPushNum, minNum, successNum, successRate, toMonthDay);
            cur.execute(updateSql)
        saveLog(logDetail, toMonthDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 50
        jobName = '	核心指标-夜间音量-推送成功率'
        tableName = 'analysis_yjyl_complete_rate'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    #today = todayYMD()
    date = getdate(1)
    monthdate = getMonthdate(1)
    #today = "2021-12-13"
    print ("%s 日期,更新<数据分析-追剧提醒-服务推送成功率>报表" % date)
    insertYjylCompleteRate(date)
    insertYjylCompleteRateMonth(monthdate)

